/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Gtk;
using Gdk;

namespace Whitemice.Calendar
{
  /// <remarks>
  /// Abstract class that contains the painting logic and interface for
  /// events on the DayStrip widget.  Applications should implement a
  /// concrete Facade for their data objects by inheriting from this
  /// object.
  /// </remarks>
  public abstract class CalendarEvent : System.IComparable
  {
    protected Rectangle rect;
    
    public CalendarEvent()
    {
      /* This ctor exists only for applications that want to 
         inherit from this object as a Facade */
    }
    
    public abstract DateTime  Start { get; set; }
    public abstract DateTime  End  { get; set; }
    public abstract string    Title { get; set; }
    public abstract string    Text { get; set; }
    public abstract Gdk.Color Background { get; set; }    
    public abstract Gdk.Color EventColor { get; set; }
    public abstract Gdk.Color BannerColor { get; set; }
    public abstract bool      Draggable { get; }

    internal virtual Rectangle Rectangle { get { return rect; } set { rect = value; } } 
   
    /// <summary>
    /// Checks if the specified coordinates are within the bounds of the 
    /// object.
    /// </summary>
    /// <param name="_x">
    /// A <see cref="System.Int32"/>
    /// </param>
    /// <param name="_y">
    /// A <see cref="System.Int32"/>
    /// </param>
    /// <returns>
    /// A <see cref="System.Boolean"/>
    /// </returns>
    public bool IsIndicated(int _x, int _y)
    {
      if ((rect.Left < _x) && (rect.Right > _x) &&
          (rect.Top < _y) && (rect.Bottom > _y))
        return true;
      return false;
    } /* end IsIndicated */
    
    /// <summary>
    /// Return a list of events from the provided list of events that overlap
    /// in time with this event.
    /// </summary>
    /// <param name="_events">
    /// A <see cref="System.Collections.Generic.IList"/>
    /// </param>
    /// <returns>
    /// A <see cref="System.Collections.Generic.List"/>
    /// </returns>
    public List<CalendarEvent> FilterOverlaps(IList<CalendarEvent> _events)
    {
      return FilterOverlapsInWindow(_events, Start, End);
    } /* GetOverlaps */
    
    /// <summary>
    /// Return a list of events from the provided list of events that overlap
    /// in time with this event on the specified day.  If this event does not
    /// occur on the the specified day the result, obviously, is always empty.
    /// </summary>
    /// <param name="_events">
    /// A <see cref="System.Collections.Generic.IList"/>
    /// </param>
    /// <param name="_day">
    /// A <see cref="System.DateTime"/>
    /// </param>
    /// <returns>
    /// A <see cref="System.Collections.Generic.List"/>
    /// </returns>
    public List<CalendarEvent> FilterOverlapsInDay(IList<CalendarEvent> _events, DateTime _day)
    {
      return FilterOverlapsInWindow(_events, _day.Date, _day.Date.AddDays(1.0));
    }
    
    /// <summary>
    /// Return a list of events from the provided list of events that overlap
    /// in time with this event within the specified window.  If this event
    /// does not occur within the specified window the result list, obviously,
    /// will always be empty.
    /// </summary>
    /// <param name="_events">
    /// A <see cref="System.Collections.Generic.IList"/>
    /// </param>
    /// <param name="_start">
    /// A <see cref="System.DateTime"/>
    /// </param>
    /// <param name="_end">
    /// A <see cref="System.DateTime"/>
    /// </param>    
    /// <returns>
    /// A <see cref="System.Collections.Generic.List"/>
    /// </returns>    
    public List<CalendarEvent> FilterOverlapsInWindow(IList<CalendarEvent> _events, 
                                                      DateTime _start, 
                                                      DateTime _end)
    {
      DateTime            tmpStart, tmpEnd;
      List<CalendarEvent> overlaps;
      
      overlaps = new List<CalendarEvent>();
      foreach(CalendarEvent e in _events)
      {
        if (Start.CompareTo(_start) < 0)
          tmpStart = _start;
        else tmpStart = Start;
        if (End.CompareTo(_end) > 0)
          tmpEnd = _end;
        else tmpEnd = End;
        if ((e.Start.CompareTo(tmpEnd) <= 0) &&
            (e.End.CompareTo(tmpStart) >= 0))
        {
          Console.WriteLine("Event {0} - {1} qualified as overlapping {2} - {3}", 
            e.Start, e.End, tmpStart, tmpEnd);
          overlaps.Add(e);
        }
      }
      return overlaps;
    } /* end FilterOverlapsInWindow */
    
    /// <summary>
    /// Used to meed to the implementation of the System.IComparable interface.
    /// Events are sorted based upon their start time,  events with later
    /// start times occur after events with earlier start times.
    /// A <see cref="System.IComparable"/>
    /// </summary>
    /// <param name="_object">
    /// A <see cref="System.Object"/>
    /// </param>
    /// <returns>
    /// A <see cref="System.Int32"/>
    /// </returns>
    public int CompareTo(object _object)
    {
      if (_object is CalendarEvent)
        return Start.CompareTo((_object as CalendarEvent).Start);
      if (_object is System.DateTime)
        return Start.CompareTo((System.DateTime)_object);
      throw new Exception(string.Format("CalendarEvent cannot be compared to {0}", _object.GetType()));
    }
    
    protected void PaintAsFancy(Style _style, 
                                Widget _widget, 
                                CalendarDay _day, 
                                Rectangle _rect)
    {
      Pango.Layout  layout;
      Gdk.Rectangle innerRect;
      Gdk.Window    drawable = _widget.GdkWindow;
      Gdk.GC        gc1 = new Gdk.GC(drawable),
                    gc2 = new Gdk.GC(drawable);
      
      gc1.RgbFgColor = EventColor;
      gc1.RgbBgColor = Background;
      gc2.RgbFgColor = BannerColor;
      gc2.RgbBgColor = Background;
      /* make layout */
      layout = new Pango.Layout(_widget.PangoContext);
      layout.FontDescription = Pango.FontDescription.FromString ("Tahoma 8");
      /* if appointment starts today the banner is the start TIME if the
         appointment begin on a previous day the banner is the DATE */
      if (Start.Date.CompareTo(_day.Date) == 0)
        layout.SetText(Start.ToString("HH:mm"));
      else layout.SetText(Start.ToString("MM/dd"));
      /* the banner text is centered */
      layout.Alignment = Pango.Alignment.Center;
      layout.Width = (Rectangle.Width - 4);  
      /* if appointment starts today paint a rounded top */
      if (Start.Date.CompareTo(_day.Date) > -1)
      {
        /* top right arc */
        drawable.DrawArc(gc2, true, 
                         (Rectangle.Right - 24), Rectangle.Y, 
                         24, 24, (0 * 64),(90 * 64));
        /* top left arc */
        drawable.DrawArc(gc2, true, 
                         Rectangle.Left, Rectangle.Top, 
                         24, 24, 
                         (90 * 64),(90 * 64));
        /* fill banner area */
        drawable.DrawRectangle(gc2, true, 
                               (Rectangle.Left + 12), (Rectangle.Top),
                               (Rectangle.Width - 24), 12);
      } else
        {
          /* appoint begins on a previous day, paint a flat top */
          /* fill banner area */
          drawable.DrawRectangle(gc2, true, 
                                 (Rectangle.Left), (Rectangle.Top),
                                 (Rectangle.Width), 12);
        }
      Style.PaintLayout(_style, 
                        _widget.GdkWindow,
                        StateType.Prelight, 
                        true, 
                        new Gdk.Rectangle((Rectangle.Left + 18), 
                                          (Rectangle.Top),
                                          (Rectangle.Width - 24), 
                                          12),
                        _widget, 
                        null,
                        (Rectangle.Left + (Rectangle.Width / 2)),
                        (Rectangle.Top + 1),
                        layout);
      /* fill body */
      drawable.DrawRectangle(gc1, true, 
                             (Rectangle.Left), (Rectangle.Top + 12),
                             (Rectangle.Width), (Rectangle.Height - 19));
      /* appointment ends on this day draw a rounded bottom */
      if (End.Date.CompareTo(_day.Date) == 0)
      {
        /* bottom right arc */
        drawable.DrawArc(gc1, true, 
                         (Rectangle.Right - 14), (Rectangle.Bottom - 14),
                         14, 14, 
                         (270 * 64),(90 * 64));                             
        /* bottom left arc */
        drawable.DrawArc(gc1, true, 
                         Rectangle.Left, (Rectangle.Bottom - 14),
                         14, 14, 
                         (180 * 64),(90 * 64));
        /* fill bottom */
        drawable.DrawRectangle(gc1, true, 
                               (Rectangle.Left + 7), (Rectangle.Bottom -7),
                              (Rectangle.Width - 14), 7);
      } else
        {
          /* end of appointment is past today so paint a flat bottom */
          drawable.DrawRectangle(gc1, true, 
                                 (Rectangle.Left), (Rectangle.Top + 12),
                                 (Rectangle.Width), (Rectangle.Height - 12));
         }
      /* put text into box if there is room for at least one row */
      if (Rectangle.Height > 28)
      {
        innerRect = new Gdk.Rectangle((Rectangle.Left + 2), /* X */ 
                                      (Rectangle.Top + 13), /* Y */
                                      (Rectangle.Width - 4), /* Width */
                                      (Rectangle.Height - 14)); /* Height */
        layout = new Pango.Layout(_widget.PangoContext);
        layout.FontDescription = Pango.FontDescription.FromString ("Tahoma 10");
        layout.SetMarkup(string.Format("<b>{0}</b>\n{1}", Title, Text));
        Style.PaintLayout(_style, 
                         _widget.GdkWindow,
                          StateType.Prelight, 
                          true, 
                          innerRect, 
                          _widget, 
                          null,
                          innerRect.Left,
                          innerRect.Top,
                          layout);
      }
    } /* end PaintAsFancy */ 
    
    protected void PaintAsSimple(Style _style, 
                                 Widget _widget, 
                                 CalendarDay _day, 
                                 Rectangle _rect)
    {
      Pango.Layout  layout;
      Gdk.Window    drawable = _widget.GdkWindow;
      Gdk.GC        gc1 = new Gdk.GC(drawable),
                    gc2 = new Gdk.GC(drawable);
      
      gc1.RgbFgColor = EventColor;
      gc1.RgbBgColor = Background;
      gc2.RgbFgColor = BannerColor;
      gc2.RgbBgColor = Background;
      /* make layout */
      layout = new Pango.Layout(_widget.PangoContext);
      layout.FontDescription = Pango.FontDescription.FromString ("Tahoma 8");
      /* if appointment starts today the banner is the start TIME if the
         appointment begin on a previous day the banner is the DATE */
      if (Start.Date.CompareTo(_day.Date) == 0)
        layout.SetText(Start.ToString("HH:mm"));
      else layout.SetText(Start.ToString("MM/dd"));
      /* the banner text is centered */
      layout.Alignment = Pango.Alignment.Center;
      layout.Width = (Rectangle.Width - 4);
      /* paint event in minimum mode since it is very small */
      _widget.GdkWindow.DrawRectangle(gc2, true, 
                                      (Rectangle.Left), (Rectangle.Top),
                                      (Rectangle.Width), (Rectangle.Height));
      Style.PaintLayout(_style, 
                        _widget.GdkWindow,
                        StateType.Prelight, 
                        true, 
                        Rectangle,
                        _widget, 
                        null,
                        (Rectangle.Left + (Rectangle.Width / 2)),
                        (Rectangle.Top + 1),
                        layout);
    } /* end PaintAsSimple */
    
    /// <summary>
    /// Paints the event onto the provided day within the prescribed rectangle.
    /// </summary>
    /// <param name="_style">
    /// A <see cref="Gdk.Style"/>
    /// </param>
    /// <param name="_widget">
    /// A <see cref="Gtk.Widget"/>
    /// </param>
    /// <param name="_day">
    /// A <see cref="Whitemice.Calendar.CalendarDay"/>
    /// </param>
    /// <param name="_rect">
    /// A <see cref="Gdk.Rectangle"/>
    /// </param>
    public void Paint(Style _style, Widget _widget, 
                      CalendarDay _day, Rectangle _rect)
    {
      Rectangle = _rect;
      if ((Rectangle.Width > 60) || (Rectangle.Height < 50))
      {
        PaintAsFancy(_style, _widget, _day, _rect);
      } else
        {
          PaintAsSimple(_style, _widget, _day, _rect);   
        }
    } /* end Paint */
  } /* end class CalendarEvent */
}
